package com.shujia.dao;

import com.shujia.bean.User;
import com.shujia.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author yangjiming
 * @create 2021-03-30 21:28
 */
public class UserDao {

    /**
     * 通过用户名查询用户
     *
     * @param username 用户名
     * @return 查询到的用户， 查询失败返回null
     */
    public User findUserByUsername(String username) {

        User user = null;

        try {
            Connection conn = JDBCUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement("select * from t_user where username = ?");
            ps.setString(1, username);

            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                int id = rs.getInt("id");
                String password = rs.getString("password");
                //String username1 = rs.getString("username");
                user = new User(id, username, password);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return user;
    }

    /**
     * 注册新用户
     *
     * @param username 新用户名
     * @param password 密码
     * @return 注册成功返回1 失败0
     */
    public int insert(String username, String password) {
        //建立数据库连接
        Connection conn = JDBCUtil.getConnection();
        int flag = 0;
        try {
            PreparedStatement ps = conn.prepareStatement("insert into t_user(username,password) values (?,?)");
            //填充占位符
            ps.setString(1, username);
            ps.setString(2, password);
            //执行插入
            flag = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return flag;
    }


    public int upadtePasswordByUsername(String username,String newPassword) {
        //建立连接
        Connection conn = JDBCUtil.getConnection();
        int flag = 0;
        try {
            PreparedStatement ps = conn.prepareStatement("update t_user set password = ? where username=?");
            ps.setString(1,newPassword);
            ps.setString(2,username);
            flag = ps.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return flag;
    }


}
